/**
 * 
 * 主要是公用的功能,一些较通用的工具与
 * 
 */
var DZQUtil={
	/**
	 * 提示输入框可输入的字数
	 * @param input:输入控件
	 * @param show：输出控件
	 * @param cnt：字数限制
	 * 
	 */
	inputCnt:function(input,show,cnt,txt){
		var e=$(input);
		function texthandler(event){
			var leng=cnt-len( e.val()) ;
			 if(!txt){
				 txt="还可输入：";
			 }
			 $(show).html(txt+ (leng>=0?leng:"<font color=red>"+leng+"</font>"));
		};
		function len(str){
			if(!str){
				return 0;
			}
			return str.length;
		}
		//增加键盘
		e.keyup(texthandler );
		e.bind('cut paste change',texthandler );
	},


    inputWCnt: function (input, show, cnt, txt) {
        var e = $(input);

        function texthandler(event) {
            var leng = cnt - len(e.val());
            if (!txt) {
                txt = "还可输入：";
            }
            $(show).html(txt + (leng >= 0 ? leng : "<font color=red>" + leng + "</font>"));
        };
        function len(str) {
            if (!str) {
                return 0;
            }
            var l = 0;
            for (var i = 0; i < str.length; i++) {
                if (str.charCodeAt(i) > 255) {
                    l += 2;
                } else {
                    l++;
                }
            }
            return Math.ceil(l / 2);
        }

        //增加键盘
        e.keyup(texthandler);
        e.bind('cut paste change', texthandler);
    }
	
};


// *********************************************  返回页面顶部的滚动效果 *********************************************
var timeout = null;
var tops = null;// chrome 不能用top做全局变量
var $window = $(window);
function scroll_Events(){
	if(!document.getElementById("btt")){
		$("body").append('<a style="opacity: 1;display:none" class="btt bttx" href="javascript:;" id="btt"></a>');
	}
	$window.scroll(function(){
		tops = $window.scrollTop();
		if( tops > 50 ){
			if(!$.browser.msie)
				$("#head").addClass("opa");
		}else{
			$("#head").removeClass("opa");
		}
		var $btt = $("#btt");
		if(tops > 1000) {
			$btt.show();
			$btt.click(function(){
				position();
			});
		}else{
			$btt.hide();
		}
	});
}
function position(){
	var p = tops - 100;
	if(p >= 0){
		setTopPosition(p);
		clearTimeout(timeout);
		timeout = setTimeout(function(){
			position();
		},0.00001);
	}
	else{
		setTopPosition(0);
		clearTimeout(timeout);
	}
}
function setTopPosition(p){
	$window.scrollTop(p);
}
//*********************************************  返回页面顶部的滚动效果 *********************************************



/**
 * ajaxLogin
 * @author lufeng
 */
var login = function(){
	var postData=$('#login_form').serialize();// 序列form,用于Ajax请求
	Wenda.post(basePath+"/users/loginAction!ajaxLogin.action", postData ,function(data){
		if(data.loginSuccess){
			setCookie('LURL',"",0);
			if(data.redirectAction==null || '' == data.redirectAction){
				$('div.modal-dialog').remove();	
				window.location.reload();
			}else{
				 
				window.location.href = basePath + data.redirectAction;
			}
		}else{
			$('#password').val('');
			$('#forLoginName').before("<div class=\"red_div\" id=\"red_message\"><span onmousedown=\"$('#red_message').remove();\">&times;</span>" + data.messages + "</div>");
		}
	},'json');
};

//================================权限校验 beg
function loginAndEmailTips(){
	if(checkLogin()){
		$("div.main").prepend('<div class="message red fontsize" style="text-align:center"><strong>你还未登录，只能浏览部分内容</strong>&nbsp;&nbsp;<a href="javascript:;" onclick="DZQCheckForUser(location.href);">立即登录</a></div>');
		return true;
	}
	else if(checkEmail()){
		$("div.main").prepend('<div class="message red fontsize" style="text-align:center"><strong>您的邮箱还未完善，赶紧完善您的邮箱，让更多圈友找到你吧！</strong>&nbsp;&nbsp;<a href="'+Constants.BASE_PATH+'users/userModifyAction!accountSafeSetting.action?flag=base&tip=addEmail">立即去完善</a></div>');
		return true;
	}else if(checkActivate()){
		$("div.main").prepend('<div class="message red fontsize" style="text-align:center"><strong>您的邮箱还未验证，赶紧验证您的邮箱，让更多圈友找到你吧！</strong>&nbsp;&nbsp;<a href="'+Constants.BASE_PATH+'users/userModifyAction!accountSafeSetting.action?flag=base&tip=email">立即去验证</a></div>');
		return true;
	}
	
}
/**
 * 电子圈用户检查
 */
function DZQCheckForUser(url,email,afterFun,loginType){
	if(checkLogin()){
		// 调用焕辉封装好的对话框
		DianziQ.openWin({
			loadUrl : Constans.BASE_PATH + "login_box.jsp",
			title : "您还没有登录，请先登录",
			afterFun : function(){
				if (url != null) {
					$("input[name='redirectAction']").val(url);
				}
				// 将登录按钮换成可以用Ajax提交的 
				$("label[name='dzq-login']").find("input[type='submit']").remove();
				$("label[name='dzq-login']").find("span").after('<input id="login_submit" type="button" tabindex="4" class="login_sub" value=" " name="button">');
				$('#login_submit').bind('click',function(){
					// 对窗口进行操作
				  	login();
				});
			}
		});
		if(loginType=='elexcon'){
			$('#modal-dialog-title-text').html('发现你是elexcon的用户，可直接登录');
			$("input[name='elexcon-userName']").val(email);// 电子展览网账号
		}
		$('#userLoginNum').val(email);// 电子圈账号
		return true;
	} else{
		return false;
	}
}

/**
 * 检查登录
 * @returns true 未登录，false 已登录
 */
function checkLogin(){
	var uid = getCookie('UID')
	if(uid == null || uid == ""){
		return true;
	}else{
		return false;
	}
}
/**
 * 检查邮箱
 * @returns true 有邮箱 ，false 没有邮箱
 */
function checkEmail(){
	var email = User.email;
	if(email==null || ""==email ){
		return true;
	}else{
		return false;
	}
}

/**
 * 检查是否激活
 * @returns true 未激活 ，false 已经激活
 */
function checkActivate(){
	var flag = User.flag;
	if(flag == 1){
		return true;
	}else{
		return false;
	}
}

/**
 * 检查用户权限
 * @param oper
 * @returns {Boolean}
 */
function checkAuth(oper){
	//所有权限DZQ_ACTIONS对象中。
	var opers = "";
	if(checkEmail())//邮箱未验证或没有邮箱
		//opers = DZQ_AUTH.UNVAL_EMAIL_AUTHS.join(",");
		opers = DZQ_AUTH.ALL_AUTHS.join(",");
	else{
		if(User.id != 0&&User.id != '')
			opers = DZQ_AUTH.ALL_AUTHS.join(",");
	}
	
	var b = (opers.indexOf(oper) >= 0);
	
	if(!b)
		checkAuthAlert(oper);
	
	return b;
}
/**
 * 未登录操作提示
 * @returns {Boolean}
 */
function loginAlert(){
	Wenda.alert("你目前是游客不能操作该功能，请先<a href='"+Constans.BASE_PATH+"login.jsp'>登录</a>","提示消息",{
		"确定" : function(){
			$(this).dialog("close");
			window.location.href = basePath;
		}
	});
	return true;
}

/**
 * 邮箱检查提示
 * @returns {Boolean}
 */
function emailAlert(){
	new DzqAlert({html:"<br/><p>很抱歉，您还没有完善邮箱，暂不支持此功能</p><p><a href='"+Constans.BASE_PATH+"users/userModifyAction!profile.action'>现在去完善邮箱>></a></p>"});
	return true;
}

/**
 * 邮箱未激活提示
 * @returns {Boolean}
 */
function activateAlert(){
	new DzqAlert({html:"<br/><p>很抱歉，您还没有验证邮箱，暂不支持此功能</p><p><a href='"+Constans.BASE_PATH+"users/userModifyAction!profile.action?flag=base&tip=email'>立即验证您的注册邮箱>></a></p>"});
	//Wenda.alert("你的邮箱未验证，无法操作该功能");
	return true;
}



/**
 * @returns true 未登录，false 已登录
 */
function loginNotice(){
	if(User.id == 0){
		//alert("你目前是游客不能操作该功能，请先登录");
		Wenda.alert("你目前是游客不能操作该功能，请先<a href='"+Constans.BASE_PATH+"login.jsp'>登录</a>","提示消息",{
			"确定" : function(){
				$(this).dialog("close");
				window.location.href = basePath;
			}
		});
		return true;
	}else{return false;}
}


/**
 * 第三方登录
 * 根据是否有邮箱来判断
 * 
 */
function isOauthUser(){
	if(checkEmail()){
		alertOauthUserMag();
		return true;
	}else{
		return false;
	}
}

//检查权限的提示
function checkAuthAlert(oper){
	Wenda.alert("你没有权限操作");
}
//对第三方用户的提示
function alertOauthUserMag(){
	var msg = "你的邮箱还没完善或验证，<a style='color:#105CB6;cursor:pointer;' href='"+Constans.BASE_PATH+"users/userModifyAction!profile.action'>现在去完善或验证&gt;&gt;</a>";
	Wenda.alert(msg,'',{
		"取消": function() {
			//your function
			$( this ).dialog( "close" );
		},
		"确定": function() {
			window.location.href = Constans.BASE_PATH+"users/userModifyAction!profile.action";
			$( this ).dialog( "close" );
		}
		});
	return "";
}
//================================权限校验 end


/**
 * 
 */
function editTagsHtml(tag){
	var text = "";
	if(tag)
		text = tag;
	else
		text = $("#searchList").children().eq(cacheData["listIndex"]).find("a").text();
	var tagHtml = "";
	// console.log("rmid-"+text);
	
	var $editTagList = $("#edit_taglist");
	if($editTagList.html().indexOf("rmid-"+text) < 0){
		tagHtml = '<span class="mods">'
				+'<a href="'+basePath+'tag/tagAction!tagindex.action?tagName='+text+'">'+text+'</a>'
				+'<a id="rmid-'+text+'" href="javascript:;" name="remove"><img src="'+Constans.IMG_BASE_URL+'authentication.gif" class="del"></a></span>';
		var $tag = $(tagHtml);
		$tag.bind("click",function(){
			$tag.remove();
			var tags = getEditTags();
			$("#q_tag").val(tags);
			Question.updateQuestion('Question.questionTagListHtml()');
		});
		$editTagList.append($tag);
		$("#editQ_tagInput").find("input").val("");
		
		var tags = getEditTags();
		$("#q_tag").val(tags);
		Question.updateQuestion('Question.questionTagListHtml()');
	}else{$("#editQ_tagInput").find("input").val("");}
}

function getEditTags(){
	var tags = "";
	$("#edit_taglist >span >a[href!='javascript:;']").each(function(){
		var txt = $(this).text();
		tags += $.trim(txt) + " ";
	});
	return tags;
}

//举报
function report(){
	// 举报问题/人
	$("a[data-type]").unbind("click");
	$("a[data-type]").bind("click",function(){
		// 检查是否登录
		if(DZQCheckForUser()){
			return;
		}
		var temp = $(this).attr("data-type");// 获取举报数据
		var type = temp.split("-")[0];
		var objId = temp.split("-")[1];
	
	
		
		Wenda.openWin({
			loadUrl:Constans.BASE_PATH+"msg/complaint.jsp #complaint-dialog",
			title:"举报",
			afterFun:function(){
				$("#complaint_cancel").bind("click",function(){
					Wenda.closeWin();
				});
				$("#send_complaint").bind("click",function(){
					var compliantReason =  $("#compliant-reason").val();
					compliantReason = $.trim(compliantReason); // 去掉两头的空格
					if(compliantReason == null || compliantReason.length == 0){
						Wenda.alert("举报理由不能为空","提示消息",{
							"确定" : function(){
								$(this).dialog("close");
							}
						});
						$("#compliant-tip").html('请说明举报原因&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font color=\'red\'>*理由不能为空</font>');
					}
					Wenda.post(basePath+"complaint/complaintAction!saveComplaint.action", {
						"type":type,
						"objId":objId,
						"detail":compliantReason
					},function(data){
						if (data.message != '') {
							if(data.message == 'no_login'){
								Wenda.alert("您还未登录,不能进行此操作.","提示消息",{
									"确定" : function(){
										$(this).dialog("close");
										window.location.href = basePath + "login.jsp";
									}
								});
							}else{
								Wenda.alert(data.message);
							}
							return;
						}
					},'json');
					Wenda.closeWin();
				});
			}
		});
	});
}

//问题反馈
function feedback(){
	$("a[id='feedback']").bind("click",function(){
		Wenda.openWin({
			loadUrl:Constans.BASE_PATH+"dialogCode.jsp #feedback",
			title:"意见反馈",
			afterFun:function(){
				$("#closefeed").bind("click",function(){
					Wenda.closeWin();	
				});
				
				$("#addfeed").bind("click",function(){
					var content =$("#addfeedback").val();
					if(content.length<10){				
						$("#xxq").css("display","block");
						return;
					}
								
				Wenda.post(
						basePath+"feedback/feedback!feedback.action",
						{
						'detail':content,
						'type':$("#select").val()
						},
						function(data){
							if(data.num==1){ 
								Wenda.alert("感谢您的反馈,我们会尽快处理！","提示消息",{
									"确定" : function(){
										$(this).dialog("close");
										Wenda.closeWin();
									}
								});
							}else{
								Wenda.alert("反馈异常！","提示消息",{
									"确定" : function(){
										$(this).dialog("close");
										Wenda.closeWin();
									}
								});
							}
						},'json');
				});
			}});
	
	});
}

/**
 * 邀请加入电子圈
 */
function inviteJoinDianziq(){
	$("#inviteLink").bind("click",function(){
		if(DZQCheckForUser())
			return;
		
	var html = '<div id="invite_a">'
			+'<div id="invite_answer">'
			+'	<div style="display: block;" id="xuq" class="xle xu" style="width: 60%">'
			+'		<div id="inputTip">邀请邮箱：</div>'
			+'		<div class="xtq xf" style="width: 80%">'
			+'			<div id="invite_users" class="xtu">'
			+'			</div>'
			+'			<div id="addQ_tagInput" class="xkw" style="width: 98%">'
			+'				<input class="xnq" id="invite_user" style="width: 100%">'
			+'			</div>'
			+'		</div>'
			+'		<div style="width: 84%; display:none;" id="invitedView">'
			+'			<div style="margin-top: 10px" id="invited_tip">已经邀请的好友：</div>'
			+'			<div id="invitedList" class="xtu"></div>'
			+'		</div>'
			+'	</div>'
			+'</div>'
			+'<div style="clear: both;"></div>'
			+'<div class="xlw">'
			+'	<a href="javascript:;" class="xfv" name="cancel" id="invite-cancel">取 消</a>'
			+'	<a href="javascript:;" class="xpw xe" name="invite" id="invite-submit">发送</a>'
			+'</div>'
		+'</div>';
		
		DianziQ.openWin({
			html:html,
			title:"邀请好友加入电子圈",
			afterFun:function(){
				$("#invitedView").show();
				
				$("#invite-cancel").bind("click",function(){
					DianziQ.closeWin();
				});
				
				//buildUserListHtml();
				queryInvitedUserList();
				
				$("#invite-submit").bind("click",function(){ 
					if(DZQCheckForUser()||isSubmit)
						return;
					if(!checkAuth(DZQ_ACTIONS.INVITE_JOIN)){
						return;
					}
					var $toEmail = $("#addQ_tags");
					if(!checkLength( $toEmail, "邮箱", 6, 80 ))return;
					//email_Regexp 在util.js中定义
					if(!checkRegexp( $("#addQ_tags"), email_Regexp, "邮箱格式不正确" ))return;
					Wenda.post(basePath+"json/userJsonAction!inviteUserRegister.action",{"email":$toEmail.val()},function(data){
						if(data.messages == ""){
							Wenda.alert("邀请发送成功");
						}else{
							Wenda.alert(data.messages);
						}
					});
					
					DianziQ.closeWin();
				});
			}
		});
			
	});
}
function queryInvitedUserList(){
	isSubmit = false;
	Wenda.post(basePath+"json/userJsonAction!queryInvitedUserList.action",null,function(data){
		if(data.messages == "success"){
			buildUserListHtml(data.invUserJoinList);
		}
	});
}

function buildUserListHtml(invUserJoinList){
	if(invUserJoinList != ""){
		var strList = "";
		for ( var i = 0; i < invUserJoinList.length; i++) {
			//strList +=  invUserJoinList[i].email + ", ";
			strList +=  '<div class="xrk"><span>'+invUserJoinList[i].email+'</span></div>';
		}
		$("#invitedList").html(strList);
	}
}


function filterDzqLinks(){
	var a=$('a[href^="http"]').each(function(index){
		var h=$(this).attr("href");

		if( h.indexOf( document.domain)<0||h.indexOf("img.dianziq.")>0){
			$(this).attr("target","_blank");
		}
		
		 
	});
	
	//.attr("target","_blank");
//	for(var i=0;i<a.length;i++){
//		a[i].attr("target","_blank");
//	}
}
$(function(){
	feedback();
	scroll_Events();
	filterDzqLinks();
	loginAndEmailTips();
	$("img").each(function(){
		var $_this = $(this);
		var attr1 = $_this.attr("dzq");
		var attr2 = $_this.attr("dzq-style");
		
		if(attr1 && attr2 && attr1.length > 1 && attr2.length > 1){
			$_this.css("maxWidth","500px");
		}
//		else if($_this.width() > 500){
//			$_this.css("maxWidth","500px");
//		}
	});
});


// ******************************************** 利用flash做图片多张上传 ************************************************
$(function() {
	// 弹出上传层
	$('input[name="__upload_album"]').bind("click", function() {
		if(photoCount >= 20){
			Wenda.alert("你已经上传了20张图片");
			return ;
		}
		var $this = $(this);
		var winTitle = $this.data("title");
		var pid = $this.data("pid");
		var maxPCount = $this.data("maxPCount") ;
		var ablumtype = $this.data("ablumtype"); // 相册类型p
		var albumname = $this.data("albumname"); // 相册名字,related:活动相关, review:活动回顾, special:专题图片
		var iframe = '<iframe id="iframedemo" src="' 
			+ Constans.BASE_PATH+'uploadify/upload.jsp?id=' + pid 
			+ '&curPCount=' + photoCount 
			+ '&maxPCount=' + maxPCount
			+ '&ablumtype=' + ablumtype
			+ '&albumname=' + albumname
			+ '&albumId=" '
			+ 'style="width: 100%;min-height: 280px;border: none;" '
			+ 'marginheight="0" '
			+ 'marginwidth="0" '
			+ 'frameborder="0" >'
			+ '</iframe>';
		Wenda.openWin({
			html:iframe+"<div class='center'><a href='javascript:;' onclick='javascript:Wenda.closeWin();'>关 闭</a></div>",
			title:winTitle != null ? winTitle : "上传活动相关图片"
		});
	});
	
	// 删除,浏览图片
	$("#gallery > li").bind("click", function(event) {
		var $item = $(this), $target = $(event.target);
		if ($target.is("a.ui-icon-trash")) {
			deleteImage($item);
		} else if ($target.is("a.ui-icon-zoomin")) {
			viewLargerImage($target);
		}
		return false;
	});
	$("#pic-review >li").bind("click", function(event) {
		var $item = $(this), $target = $(event.target);
		if ($target.is("a.ui-icon-trash")) {
			deleteImage($item);
		} else if ($target.is("a.ui-icon-zoomin")) {
			viewLargerImage($target);
		}
		return false;
	});
	
	
});

var photoCount = 0;
function getPhotoCount(){
	return photoCount;
}
function setPhotoCount(photoCount){
	photoCount = photoCount;
}

//给上传空间的子窗口调用
function setiframeHeight(heigh){
	$("#iframedemo").height(heigh+15);
}

// 返回的数据
function upLoadResponse(response){
	var html = '' + 
	'<li class="ui-widget-content ui-corner-tr ui-draggable">' + 
  		"<img src='"+Constans.IMG_BASE_URL+"l_"+response.filename+"' img='"+response.filename+"' data-src='"+Constans.IMG_BASE_URL+response.filename+"' data-id='"+response.photoId+"'/>" ;
  		if (response.albumname != null && response.albumname == 'review') {
  			html += '<div class="add_photos_text"><span class="grey">请填写图片标题：</span> </br>' + 
  			'<input name="review-img" data-id="' + response.photoId + '" value="" style="width:125px;" type="text"/>' + 
  			'</div>' ;
  		}
  		html += '<div class="icon_btn_div"><a class="ui-icon ui-icon-zoomin fr" title="大图" href="javascript:;" data-src="'+Constans.IMG_BASE_URL+response.filename+'" onclick="javascript:viewLargerImage($(this));">大图</a>' + 
  		'<a class="ui-icon ui-icon-trash" title="删除" href="javascript:;" onclick="javascript:deleteImage($(this).closest(\'li\'));" data-id="'+response.photoId+'">删除</a></div>' + 
	'</li>' ;
	
	
//	var html = '<li class="ui-widget-content ui-corner-tr ui-draggable">'
//		+"<img src='"+Constans.IMG_BASE_URL+"l_"+response.filename+"' img='"+response.filename+"' data-src='"+Constans.IMG_BASE_URL+response.filename+"' data-id='"+response.photoId+"'/>"
//		+'<div class="icon_btn_div"><a class="ui-icon ui-icon-zoomin fr" title="大图" href="javascript:;" data-src="'+Constans.IMG_BASE_URL+response.filename+'" onclick="javascript:viewLargerImage($(this));">大图</a>'
//		+'<a class="ui-icon ui-icon-trash" title="删除" href="javascript:;" onclick="javascript:deleteImage($(this).closest(\'li\'));" data-id="'+response.photoId+'">删除</a></div>' ;
//	if (response.albumname != null && response.albumname == 'review') {
//		html += '图片描述: <input name="review-img" data-id="'+response.photoId+'" value="" style="width:95px;"/>' ;
//	}
//	html += '</li>'; 
	
	$("#gallery").append(html);
	if (response.albumname != null && response.albumname == 'review') {
		$("#__imgDescribeSave").show();
	} else {
		// party create 1
		
	}
	photoCount = $("#pic-review").children().length + $("#gallery").children().length;
}

// 删除图片
function deleteImage( $item ) {
	var imgId = $item.find("img").attr("data-id");
	DianziQ.post(Constans.BASE_PATH+'party/partyaction!removePhoto.action',{imgId:imgId},function(data){
		$item.fadeOut(function() {
			$item.remove();
		});
		photoCount--;
	});
}

// 浏览大图
function viewLargerImage( $link ) {
	var src = $link.attr("data-src");
	setTimeout(function() {
		Wenda.openWin({
			html:"<img alt='' style='padding: 8px;' src='"+src+"' />",
			title:"图片浏览",
			scroll:"true"
		});
	}, 1 );
}
